package cn.kgc.day05.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 课工场
 * @date 2024/10/17
 * @description 非法请求拦截    受限资源需要用户认证之后访问  非受限资源可直接访问
 * <p>
 * filter 生命周期     自动调用
 * <p>
 * init     项目启动时
 * <p>
 * doFilter    匹配一次请求 调用一次
 * <p>
 * destroy    容器关闭时
 */
@WebFilter("/*")
public class CustomerLoginFilter implements Filter {

    //  过滤器初始化方法
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("----------CustomerLoginFilter init------------");
    }

    //  CustomerLoginFilter  正常访问拦截  放行 chain.doFilter();  拦截   不调用chain.doFilter();
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("----------CustomerLoginFilter doFilter------------");

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //  判定请求资源    非受限资源
        String requestURI = req.getRequestURI();
        System.out.println("requestURI = " + requestURI);
        // login.jsp  register.jsp
        if ("/javaweb/login.jsp".equals(requestURI) || "/javaweb/register.jsp".equals(requestURI)) {
            chain.doFilter(req, resp);
            return;
        }

        //  /user?method=login   /user?method=registerUser
        String method = req.getParameter("method");
        System.out.println("method = " + method);
        if ("login".equals(method) || "registerUser".equals(method)) {
            chain.doFilter(req, resp);
            return;
        }

        // 访问受限资源    session
        HttpSession session = req.getSession();
        Object username = session.getAttribute("username");
        if (username==null){  // 没有认证  重定向到登录页
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
            return;
        }

        chain.doFilter(request, response);
    }


    //  过滤器销毁方法
    @Override
    public void destroy() {
        System.out.println("----------CustomerLoginFilter destroy------------");
    }
}
